<template>
  <div class="app-container">
    <el-radio-group v-model="queryParams.pushType" @change="getList" style="margin-bottom: 30px;">
      <el-radio-button v-for="(item,index) in tabList" :key="index" :label="item.value">{{item.label || ''}}</el-radio-button>
    </el-radio-group>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:faParkProject:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="项目名称" align="center" prop="name" />
      <el-table-column label="项目代号" align="center" prop="code" show-overflow-tooltip />
      <!-- <el-table-column label="推送类型" align="center" prop="pushType">
        <template slot-scope="{row}">
          <dict-tag :options="dict.type.project_push_type" :value="row.pushType"/>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-hasPermi="['system:faParkProject:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
            v-hasPermi="['system:faParkProject:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目代号" prop="code">
          <el-input v-model="form.code" placeholder="请输入项目代号" />
        </el-form-item>
        <el-form-item label="项目地址" prop="baseUrl">
          <el-input v-model="form.baseUrl" placeholder="请输入项目地址" />
        </el-form-item>
        <div v-if="form.id">
          <el-row v-for="(item,index) in form.pushConfigList" :key="index">
            <el-col :span="12">
              <el-form-item label="推送地址" prop="noticeUrl">
                <el-input v-model="item.noticeUrl" placeholder="请输入推送地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="推送类型" prop="deviceType">
                <div class="flex_hcneter">
                  <el-select v-model="item.deviceType" class="flex_flex" style="margin-right:10px;" placeholder="请选择推送类型">
                    <el-option :disabled="getTypeStatus(item1.enumValue,index)"
                      v-for="item1 in deciveList"
                      :key="item1.enumValue"
                      :label="item1.name"
                      :value="item1.enumValue">
                    </el-option>
                  </el-select>
                  <el-button type="primary" icon="el-icon-plus" @click="addList()"></el-button>
                  <el-button v-if="form.pushConfigList.length > 1" type="primary" @click="delList(index)" icon="el-icon-minus"></el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, addFaParkProject, updateFaParkProject, delFaParkProject,getPushUrlList,} from "@/api/config/projectPushManage";
import { selectFaDeviceType,} from "@/api/config/deviceType";
export default {
  name: "ProjectPushManage",
  dicts: ['project_push_type'],
  data() {
    return {
      tabPosition:1,
      tabList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        pushType:1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        code: [{ required: true, message: "项目代号不能为空", trigger: "blur" }],
        baseUrl: [{ required: true, message: "项目地址不能为空", trigger: "blur" }],
        // pushType: [{ required: true, message: "推送类型不能为空", trigger: "change" }],
      },
      nbtsPermission:'system:faParkProjectPushConfig:list',
      wbtsPermission:'system:faParkProject:wblist',
      deciveList:[],//设备类型数据
    };
  },
  created() {
    const user = this.$store.state.user
    const permissions = user.permissions
    const flag = !!permissions.find(item => item == this.nbtsPermission)
    const flag1 = !!permissions.find(item => item == this.wbtsPermission)
    if (flag || permissions[0] == '*:*:*'){
      this.queryParams.pushType = 1
      this.tabList.push({value: 1,label:'内部推送'})
    }else if(flag1 || permissions[0] == '*:*:*'){
      this.queryParams.pushType = 2
    }
    if(flag1 || permissions[0] == '*:*:*') this.tabList.push({value: 2,label:'外部推送'})
    this.getList();
  },
  methods: {
    getTypeStatus(value,index){//获取当
      return this.form.pushConfigList.find((item,index1)=>item.deviceType == value && index1 != index) ? true : false
    },
    addList(){//添加列表
      this.form.pushConfigList.push({})
    },
    delList(index){//删除列表
      this.form.pushConfigList.splice(index,1)
    },
    async selectFaDeviceType(){
      let res = await selectFaDeviceType()
      let data = res.data || []
      this.deciveList = data
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      let queryParams = {...this.queryParams}
      getList(queryParams).then(response => {
          this.list = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {pushType:1};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目推送管理";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.form = {...row,pushType:row.pushType || 1};

      this.open = true;
      this.title = "修改项目推送管理";
      this.selectFaDeviceType()
      let res = await getPushUrlList({
        pushType:this.queryParams.pushType,
        fkProjectId:row.id,
      })
      let data = res.data || []
      let form = {...this.form}
      form.pushConfigList = data.length ? data : [{}]
      this.form = {...form}
    },
    getStrNull(str){//判断是否为空
      return str === '' || str === null || str === undefined
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          form.pushType = this.queryParams.pushType
          let pushConfigList = form.pushConfigList || []
          let flag = false
          form.pushConfigList = pushConfigList.map(item=>{
            if(this.getStrNull(item.noticeUrl) || this.getStrNull(item.deviceType)) flag = true
            return {
              ...item,pushType:this.queryParams.pushType,
            }
          })
          if(flag) return this.$modal.msgWarning("请填写完整的推送地址或设备类型");
          if (this.form.id != undefined) {
            updateFaParkProject(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFaParkProject(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delFaParkProject({id:dictIds});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>